import utils from './../utils'
import * as types from '../constants/shop'
import store from 'store'



//获取指定店铺的分组列表
export const getGroupList =(data,config={})=>{
	data= {...data,...{func:'group-list',company_id:1}}
    return (dispatch,getState)=>{
	return utils.form(utils.url.index,data)
	.then(res=>{
		if(res.code == 200)
		  return dispatch({type:types.GET_GROUP_LIST,data:res.data})
	})
	}

}


//通过分组ID获取分组/分组项商品
export const getGroupGoods =(data,callBack:()=>{})=>{
	data= {...data,...{func:'group-goods-list'}}
	return utils.form(utils.url.index,data)
	.then(res=>{
		 callBack && callBack(res)

	})
	
}

//获取分类中的商品列表
export const getCateGoods =(data,callBack:()=>{})=>{
	data= {...data,...{func:'cate-goods'}}
		return utils.form(utils.url.index,data)
		.then(res=>{
			callBack && callBack(res)
		
		})
	
}

//获取分类列表
export const getCateList =(data,config={})=>{
	data= {...data,...{func:'cate-list',company_id:1}}
    return (dispatch,getState)=>{
    	const options = getState().cateList.toJS()
    	if(options.length >0)  return dispatch({type:types.GET_CATE_LIST,data:options})
		return utils.form(utils.url.index,data)
		.then(res=>{
			if(res.code == 200)
			   return dispatch({type:types.GET_CATE_LIST,data:res.data})
		})
	}
}


//保存被选中的分类项
export const setSelectedCate =(data)=>{
	return (dispatch,getState)=>{
		let options =getState().cateList.toJS()
		if(options.length >0){
			let selectedItem=options.find(item => item.category_id == data[0])
			if(data.length > 1){
				selectedItem=selectedItem.children.find(item => item.category_id == data[1])
			}

			return dispatch({type:types.SELECTED_CATE,data:{category_id:selectedItem.category_id,category_name:selectedItem.category_name}})
		}else{
			return utils.form(utils.url.index,data)
			.then(res=>{
				if(res.code == 200)
				{
					let selectedItem=res.data.find(item => item.category_id == data[0])
					if(data.length > 1){
						selectedItem=selectedItem.children.find(item => item.category_id == data[1])
					}
				   return dispatch({type:types.SELECTED_CATE,data:{category_id:selectedItem.category_id,category_name:selectedItem.category_name}})
				}
			})
		}
	}
}


































